# coding: utf-8
from typing import Union

from PySide6.QtCore import Qt, QUrl, Signal
from PySide6.QtWidgets import QFrame, QWidget, QHBoxLayout, QLabel, QVBoxLayout

from .ffpy_media_player import FFmpegMediaPlayer
from ..common import logger, Icon
from ..widgets import TransparentToolButton, ClickableSlider


class PlayButton(TransparentToolButton):
    def _postInit(self):
        self.setIcon(Icon.PLAY)

    def setPlaying(self, playing: bool):
        if playing:
            self.setIcon(Icon.PLAY)
        else:
            self.setIcon(Icon.PAUSE)


class VolumeButton(TransparentToolButton):

    def setMuted(self, muted: bool):
        if muted:
            self.setIcon(Icon.VOLUME)
        else:
            self.setIcon(Icon.PAUSE)


class PlayerBar(QFrame):
    fullScreenChanged = Signal(bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.verticalLayout = QVBoxLayout(self)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout_2 = QHBoxLayout()
        self.playButton = TransparentToolButton(Icon.PLAY, self)
        self.currentTimeLabel = QLabel('00:00', self)
        self.progressSlider = ClickableSlider(Qt.Orientation.Horizontal, self)
        self.remainTimeLabel = QLabel('00:00', self)
        self.volumeButton = TransparentToolButton(Icon.VOLUME, self)
        self.volumeSlider = ClickableSlider(Qt.Orientation.Horizontal, self)
        self.fullscreenButton = TransparentToolButton(Icon.FULLSCREEN, self)

        self.player = FFmpegMediaPlayer(self)
        self.__initWidgets()

    def __initWidgets(self):
        self.setFixedHeight(80)
        self.volumeSlider.setValue(30)
        self.volumeSlider.setMinimumWidth(150)

        self.fullscreenButton.setToolTip('全屏')

        self.currentTimeLabel.setObjectName('CaptionLabel')
        self.remainTimeLabel.setObjectName('CaptionLabel')
        self.progressSlider.setObjectName('progressSlider')
        self.volumeSlider.setObjectName('volumeSlider')

        self.__initLayout()
        self.__connectSignals()
        self.setStyleSheet(
            'PlayerBar { background-color: rgba(40, 40, 40, 200); border-radius: 5px;} QLabel#CaptionLabel { color: white; font-size: 12px; }')

    def __initLayout(self):
        self.horizontalLayout.addWidget(self.currentTimeLabel)
        self.horizontalLayout.addWidget(self.progressSlider)
        self.horizontalLayout.addWidget(self.remainTimeLabel)
        self.verticalLayout.addLayout(self.horizontalLayout, 1)
        self.horizontalLayout_2.addWidget(self.playButton, 0, Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout_2.addStretch(1)
        self.horizontalLayout_2.addWidget(self.volumeButton)
        self.horizontalLayout_2.addWidget(self.volumeSlider)
        self.horizontalLayout_2.addWidget(self.fullscreenButton)
        self.verticalLayout.addLayout(self.horizontalLayout_2)

    def __connectSignals(self):
        self.player.durationChanged.connect(self.progressSlider.setMaximum)
        self.player.positionChanged.connect(self._onPositionChanged)
        self.playButton.clicked.connect(self.player.toggle)
        self.player.playingChanged.connect(self._onPlayingChanged)
        self.volumeButton.clicked.connect(self._onVolumeButtonClicked)
        self.volumeSlider.valueChanged.connect(self.player.setVolume)
        self.fullscreenButton.clicked.connect(self._onFullscreenButtonClicked)
        self.progressSlider.sliderReleased.connect(self._onSliderReleased)
        self.progressSlider.clicked.connect(self._onSliderReleased)

    def _onPositionChanged(self, position: int):
        self.progressSlider.setValue(position)
        self.currentTimeLabel.setText(self._formatTime(position))
        self.remainTimeLabel.setText(self._formatTime(self.player.duration() - position))

    def _onSliderReleased(self):
        try:
            self.player.setPosition(self.progressSlider.value())
        except Exception as e:
            logger.error(f'error: {e}')

    def _onPlayingChanged(self, state: bool):
        if state:
            self.playButton.setIcon(Icon.PAUSE)
        else:
            self.playButton.setIcon(Icon.PLAY)

    def _onVolumeButtonClicked(self):
        if self.player.isMuted():
            self.player.setMuted(False)
            self.volumeButton.setIcon(Icon.VOLUME)
        else:
            self.player.setMuted(True)
            self.volumeButton.setIcon(Icon.MUTE)

    def _onFullscreenButtonClicked(self):
        if self.fullscreenButton.toolTip() == '全屏':
            self.fullscreenButton.setToolTip('退出全屏')
            self.fullscreenButton.setIcon(Icon.BACK_TO_WINDOW)
            self.fullScreenChanged.emit(True)
        else:
            self.fullscreenButton.setToolTip('全屏')
            self.fullscreenButton.setIcon(Icon.FULLSCREEN)
            self.fullScreenChanged.emit(False)

    def _formatTime(self, time: int):
        s = time % 60
        m = int(time / 60)
        h = int(time / 3600)
        if h > 0:
            return f'{h}:{m:02}:{s:02}'
        else:
            return f'{m:02}:{s:02}'

    def skipBack(self, ms: int):
        """ Back up for specified milliseconds """
        self.player.setPosition(self.player.position() - ms)

    def skipForward(self, ms: int):
        """ 快进指定毫秒数 """
        self.player.setPosition(self.player.position() + ms)

    def setSource(self, source: Union[QUrl, str]):
        self.player.setSource(source)

    def setVideoOutput(self, widget: QWidget):
        self.player.setVideoOutput(widget)
